Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.93% covered (success)
94.93%
131 / 138
60.00% covered (warning)
60.00%
3 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApieServiceProvider
94.93% covered (success)
94.93%
131 / 138
60.00% covered (warning)
60.00%
3 / 5
31.13
0.00% covered (danger)
0.00%
0 / 1
 autoTagHashmapActions
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
4.00
 boot
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
 register
92.41% covered (success)
92.41%
73 / 79
0.00% covered (danger)
0.00%
0 / 1
18.14
 parseConfig
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
4
 sanitizeConfig
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2namespace Apie\LaravelApie;
3
4use Apie\AiInstructor\AiInstructorServiceProvider;
5use Apie\ApieCommonPlugin\ApieCommonPluginServiceProvider;
6use Apie\ApieFileSystem\ApieFileSystemServiceProvider;
7use Apie\CmsApiDropdownOption\CmsDropdownServiceProvider;
8use Apie\Common\CommonServiceProvider;
9use Apie\Common\ContextBuilders\FrameworkContextBuilder;
10use Apie\Common\Interfaces\BoundedContextSelection;
11use Apie\Common\Interfaces\DashboardContentFactoryInterface;
12use Apie\Common\Wrappers\BoundedContextHashmapFactory;
13use Apie\Common\Wrappers\ConsoleCommandFactory as CommonConsoleCommandFactory;
14use Apie\Console\ConsoleServiceProvider;
15use Apie\Core\CoreServiceProvider;
16use Apie\Core\Session\CsrfTokenProvider;
17use Apie\DoctrineEntityConverter\DoctrineEntityConverterProvider;
18use Apie\DoctrineEntityDatalayer\Commands\ApieUpdateIdfCommand;
19use Apie\DoctrineEntityDatalayer\DoctrineEntityDatalayerServiceProvider;
20use Apie\DoctrineEntityDatalayer\EntityReindexer;
21use Apie\DoctrineEntityDatalayer\IndexStrategy\BackgroundIndexStrategy;
22use Apie\DoctrineEntityDatalayer\IndexStrategy\DirectIndexStrategy;
23use Apie\DoctrineEntityDatalayer\IndexStrategy\IndexAfterResponseIsSentStrategy;
24use Apie\DoctrineEntityDatalayer\IndexStrategy\IndexStrategyInterface;
25use Apie\Faker\FakerServiceProvider;
26use Apie\HtmlBuilders\ErrorHandler\CmsErrorRenderer;
27use Apie\HtmlBuilders\HtmlBuilderServiceProvider;
28use Apie\LaravelApie\Config\LaravelConfiguration;
29use Apie\LaravelApie\ContextBuilders\CsrfTokenContextBuilder;
30use Apie\LaravelApie\ContextBuilders\RegisterBoundedContextActionContextBuilder;
31use Apie\LaravelApie\ContextBuilders\SessionContextBuilder;
32use Apie\LaravelApie\ErrorHandler\ApieErrorRenderer;
33use Apie\LaravelApie\ErrorHandler\Handler;
34use Apie\LaravelApie\Providers\CmsServiceProvider;
35use Apie\LaravelApie\Providers\SecurityServiceProvider;
36use Apie\LaravelApie\Wrappers\Cms\DashboardContentFactory;
37use Apie\LaravelApie\Wrappers\Core\BoundedContextSelected;
38use Apie\LaravelApie\Wrappers\Queue\BackgroundProcessPersistListener;
39use Apie\Maker\MakerServiceProvider;
40use Apie\McpServer\McpServerServiceProvider;
41use Apie\RestApi\RestApiServiceProvider;
42use Apie\SchemaGenerator\SchemaGeneratorServiceProvider;
43use Apie\Serializer\SerializerServiceProvider;
44use Apie\ServiceProviderGenerator\TagMap;
45use Apie\TypescriptClientBuilder\TypescriptClientBuilderServiceProvider;
46use Apie\Webdav\WebdavServiceProvider;
47use Illuminate\Config\Repository;
48use Illuminate\Contracts\Debug\ExceptionHandler;
49use Illuminate\Contracts\Events\Dispatcher;
50use Illuminate\Support\ServiceProvider;
51use Psr\EventDispatcher\EventDispatcherInterface;
52use Psr\Http\Message\ServerRequestInterface;
53use Symfony\Component\Config\ConfigCache;
54use Symfony\Component\Config\Definition\Processor;
55use Symfony\Component\Config\Resource\ReflectionClassResource;
56use Symfony\Component\Console\Application;
57use Symfony\Component\EventDispatcher\EventDispatcher;
58use Symfony\Component\Lock\LockFactory;
59
60class ApieServiceProvider extends ServiceProvider
61{
62    /**
63     * @var array<string, class-string<ServiceProvider>> $alreadyRegistered
64     */
65    private array $alreadyRegistered = [];
66    /**
67     * @var array<string, array<int, class-string<ServiceProvider>>> $dependencies
68     */
69    private array $dependencies = [
70        'enable_ai_instructor' => [
71            AiInstructorServiceProvider::class,
72        ],
73        'enable_common_plugin' => [
74            ApieCommonPluginServiceProvider::class,
75        ],
76        'enable_cms' => [
77            CommonServiceProvider::class,
78            HtmlBuilderServiceProvider::class, // it's important that this loads before CmsServiceProvider!!!
79            CmsServiceProvider::class,
80            SerializerServiceProvider::class,
81        ],
82        'enable_cms_dropdown' => [
83            CommonServiceProvider::class,
84            CmsDropdownServiceProvider::class,
85        ],
86        'enable_core' => [
87            CoreServiceProvider::class,
88        ],
89        'enable_console' => [
90            CommonServiceProvider::class,
91            ConsoleServiceProvider::class, // it's important that this loads after CommonServiceProvider!!!
92            SerializerServiceProvider::class,
93        ],
94        'enable_doctrine_entity_converter' => [
95            CoreServiceProvider::class,
96            DoctrineEntityConverterProvider::class,
97        ],
98        'enable_doctrine_entity_datalayer' => [
99            CoreServiceProvider::class,
100            DoctrineEntityConverterProvider::class,
101            DoctrineEntityDatalayerServiceProvider::class,
102        ],
103        'enable_security' => [
104            CommonServiceProvider::class,
105            SerializerServiceProvider::class,
106            SecurityServiceProvider::class,
107        ],
108        'enable_rest_api' => [
109            CommonServiceProvider::class,
110            RestApiServiceProvider::class,
111            SchemaGeneratorServiceProvider::class,
112            SerializerServiceProvider::class,
113        ],
114        'enable_faker' => [
115            FakerServiceProvider::class,
116        ],
117        'enable_maker' => [
118            MakerServiceProvider::class,
119        ],
120        'enable_mcp_server' => [
121            CommonServiceProvider::class,
122            SerializerServiceProvider::class,
123            McpServerServiceProvider::class,
124        ],
125        'enable_typescript_client_builder' => [
126            TypescriptClientBuilderServiceProvider::class,
127        ],
128        'enable_webdav' => [
129            ApieFileSystemServiceProvider::class,
130            WebdavServiceProvider::class,
131        ]
132    ];
133
134    private function autoTagHashmapActions(): void
135    {
136        $boundedContextConfig = config('apie.bounded_contexts');
137        $scanBoundedContextConfig = config('apie.scan_bounded_contexts');
138        $factory = new BoundedContextHashmapFactory(
139            $boundedContextConfig ?? [],
140            $scanBoundedContextConfig ?? [],
141            new EventDispatcher(),
142        );
143        $hashmap = $factory->create();
144        foreach ($hashmap as $boundedContext) {
145            foreach ($boundedContext->actions as $action) {
146                $class = $action->getDeclaringClass();
147                if (!$class->isInstantiable()) {
148                    continue;
149                }
150                $className = $class->name;
151                TagMap::register(
152                    $this->app,
153                    $className,
154                    ['apie.context']
155                );
156            }
157        }
158    }
159
160    public function boot(): void
161    {
162        $this->autoTagHashmapActions();
163        $this->loadViewsFrom(__DIR__ . '/../templates', 'apie');
164        $this->loadRoutesFrom(__DIR__.'/../resources/routes.php');
165        TagMap::registerEvents($this->app);
166
167        if ($this->app->runningInConsole()) {
168            $commands = [];
169            $commands[] = ApieUpdateIdfCommand::class;
170            // for some reason these are not called in integration tests without re-registering them
171            foreach (TagMap::getServiceIdsWithTag($this->app, 'console.command') as $taggedCommand) {
172                $serviceId = 'apie.console.tagged.' . $taggedCommand;
173                $this->app->singleton($serviceId, function () use ($taggedCommand) {
174                    return $this->app->get($taggedCommand);
175                });
176                $commands[] = $serviceId;
177            }
178            /** @var CommonConsoleCommandFactory $factory */
179            $factory = $this->app->get('apie.console.factory');
180            foreach ($factory->create($this->app->get(Application::class)) as $command) {
181                $serviceId = 'apie.console.registered.' . $command->getName();
182                $this->app->instance($serviceId, $command);
183                $commands[] = $serviceId;
184            }
185            $this->commands($commands);
186        }
187    }
188
189    public function register()
190    {
191        $this->mergeConfigFrom(__DIR__ . '/../resources/apie.php', 'apie');
192
193        $this->app->bind(FrameworkContextBuilder::class, function () {
194            return new FrameworkContextBuilder('laravel');
195        });
196        TagMap::register($this->app, FrameworkContextBuilder::class, ['apie.core.context_builder']);
197
198        // add PSR-14 support if needed:
199        if (!$this->app->bound(EventDispatcherInterface::class)) {
200            $this->app->bind(EventDispatcherInterface::class, function () {
201                return new class($this->app->make(Dispatcher::class)) implements EventDispatcherInterface {
202                    public function __construct(private readonly Dispatcher $dispatcher)
203                    {
204                    }
205
206                    public function dispatch(object $event): object
207                    {
208                        $this->dispatcher->dispatch($event);
209                        return $event;
210                    }
211                };
212            });
213        }
214
215        // fix for https://github.com/laravel/framework/issues/30415
216        $this->app->extend(
217            ServerRequestInterface::class,
218            function (ServerRequestInterface $psrRequest) {
219                $route = $this->app->make('request')->route();
220                if ($route) {
221                    $parameters = $route->parameters();
222                    foreach ($parameters as $key => $value) {
223                        $psrRequest = $psrRequest->withAttribute($key, $value);
224                    }
225                }
226                return $psrRequest;
227            }
228        );
229
230        $this->app->bind(IndexStrategyInterface::class, function () {
231            $config = config();
232            if ($config->get('apie.enable_doctrine_entity_datalayer')) {
233                $type = $config->get('apie.doctrine.indexing.type', 'direct');
234                return match ($type) {
235                    'direct' => new DirectIndexStrategy($this->app->get(EntityReindexer::class)),
236                    'late' => new IndexAfterResponseIsSentStrategy($this->app->get(EntityReindexer::class)),
237                    'background' => new BackgroundIndexStrategy(),
238                    default => $this->app->get(config('apie.doctrine.indexing.service', DirectIndexStrategy::class)),
239                };
240            }
241
242            return new DirectIndexStrategy($this->app->get(EntityReindexer::class));
243        });
244
245        $this->app->bind(ApieErrorRenderer::class, function () {
246            return new ApieErrorRenderer(
247                $this->app->bound(CmsErrorRenderer::class) ? $this->app->make(CmsErrorRenderer::class) : null,
248                $this->app->make(\Apie\Common\ErrorHandler\ApiErrorRenderer::class),
249                config('apie.cms.base_url')
250            );
251        });
252
253        $this->app->extend(ExceptionHandler::class, function (ExceptionHandler $service) {
254            return new Handler($this->app, $service);
255        });
256
257        $this->app->bind(LockFactory::class, function () {
258            $config = config('apie.lock_store');
259            return new LockFactory($this->app->get($config));
260        });
261        
262        $this->app->bind(DashboardContentFactoryInterface::class, DashboardContentFactory::class);
263        $this->app->bind(BoundedContextSelection::class, BoundedContextSelected::class);
264
265        $this->alreadyRegistered = [];
266        $parsedConfig = $this->parseConfig(config('apie'));
267        foreach ($this->dependencies as $configKey => $dependencies) {
268            if ($parsedConfig[$configKey] ?? false) {
269                foreach ($dependencies as $dependency) {
270                    if (!isset($this->alreadyRegistered[$dependency])) {
271                        $this->alreadyRegistered[$dependency] = $dependency;
272                        $this->app->register($dependency);
273                    }
274                }
275            }
276        }
277
278        //$this->app->bind(CsrfTokenProvider::class, CsrfTokenContextBuilder::class);
279        TagMap::register($this->app, CsrfTokenContextBuilder::class, ['apie.core.context_builder']);
280        $this->app->tag(CsrfTokenContextBuilder::class, ['apie.core.context_builder']);
281
282        // this has to be added after CsrfTokenContextBuilder!
283        $this->app->bind(SessionContextBuilder::class);
284        TagMap::register($this->app, SessionContextBuilder::class, ['apie.core.context_builder']);
285        $this->app->tag(SessionContextBuilder::class, ['apie.core.context_builder']);
286
287        TagMap::register($this->app, RegisterBoundedContextActionContextBuilder::class, ['apie.core.context_builder']);
288        $this->app->tag(RegisterBoundedContextActionContextBuilder::class, ['apie.core.context_builder']);
289        $this->app->extend('config', function (Repository $config) {
290            $this->sanitizeConfig($config);
291            $newParsedConfig = $config->get('apie');
292            foreach ($this->dependencies as $configKey => $dependencies) {
293                if ($newParsedConfig[$configKey] ?? false) {
294                    foreach ($dependencies as $dependency) {
295                        if (!isset($this->alreadyRegistered[$dependency])) {
296                            $this->alreadyRegistered[$dependency] = $dependency;
297                            $this->app->register($dependency);
298                        }
299                    }
300                }
301            }
302            return $config;
303        });
304
305        TagMap::register($this->app, BackgroundProcessPersistListener::class, ['kernel.event_subscriber']);
306    }
307
308    /**
309     * @param array<string, mixed> $rawConfig
310     * @return array<string, mixed>
311     */
312    private function parseConfig(array $rawConfig): array
313    {
314        $path = storage_path('framework/cache/apie-config' . md5(json_encode($rawConfig)) . '.php');
315        $resources = [
316            new ReflectionClassResource(new \ReflectionClass(LaravelConfiguration::class)),
317            new ReflectionClassResource(new \ReflectionClass(static::class)),
318        ];
319        $configCache = new ConfigCache($path, true);
320        if ($configCache->isFresh()) {
321            $processedConfig = require $path;
322        } else {
323            $configuration = new LaravelConfiguration();
324
325            $processor = new Processor();
326
327            $processedConfig = $processor->processConfiguration($configuration, ['apie' => $rawConfig]);
328
329            if (!isset($processedConfig['scan_bounded_contexts'])) {
330                $processedConfig['scan_bounded_contexts'] = [];
331            }
332            if (empty($processedConfig['storage'])) {
333                $processedConfig['storage'] = null;
334            }
335            $code = '<?php' . PHP_EOL . 'return ' . var_export($processedConfig, true) . ';';
336            $configCache->write($code, $resources);
337        }
338
339        return $processedConfig;
340    }
341
342    private function sanitizeConfig(Repository $config): void
343    {
344        $rawConfig = $config->get('apie');
345        $processedConfig = $this->parseConfig($rawConfig);
346
347        $config->set('apie', $processedConfig);
348    }
349}